package com.app.GoCuro;

import com.app.GoCuro.data.LoginResponse;
import com.app.GoCuro.util.CustomHttpClient;
import com.app.GoCuro.util.ErrorMessageCreator;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity implements Runnable 
{
	private LoginResponse loginResponse;
	private CustomHttpClient client;
	private ProgressDialog pd_login;
	private EditText loginText;
	private EditText loginPw;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        client = new CustomHttpClient(this);
        Button loginButton = (Button) findViewById(R.id.login_button);
        
        loginButton.setOnClickListener(new View.OnClickListener() 
        {
			
			@Override
			public void onClick(View v) 
			{
		
				//get the text from the two textboxes
				loginText = (EditText) findViewById(R.id.login_name_text);
				loginPw = (EditText) findViewById(R.id.login_pw_text);
				
				pd_login = ProgressDialog.show(LoginActivity.this, "", "Logging in...");			
				
				Thread thread = new Thread(LoginActivity.this);
				thread.start();
			}
		});
    }
    
    /*
     * Handler for when login thread stops
     */
    private Handler handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		pd_login.dismiss();
    		
			//only start the next activity if you got a non null response to the string
			if (loginResponse.getSucceeded())
			{					
				Intent selectDatabaseIntent = new Intent(LoginActivity.this, SelectDatabaseActivity.class);
				LoginActivity.this.startActivity(selectDatabaseIntent);
			}
			else
			{
				ErrorMessageCreator.CreateErrorMessage(LoginActivity.this, loginResponse.getErrorString());
			}
    	}
    };

    /*
     * Runner thread, attempts to login to the database, sending a message to the handler on completion
     */
	@Override
	public void run() 
	{
		loginResponse = client.login(loginText.getText().toString(), loginPw.getText().toString());
		pd_login.dismiss();
		handler.sendEmptyMessage(0);		
	};
		
}